package com.storlead.sjwt.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Optional;

/**
 * @Author: Timo
 * @Date: 2019/3/21 10:43
 * @Description: JSON WEB TOKEN 工具类
 */
public class JwtTokenUtils {
    private static Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);
    public static final String TOKEN_HEADER = "loginToken";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "echisan";
    // 角色的key
    private static final String ROLE_CLAIMS = "rol";

    // 过期时间是3600秒，既是1个小时
    private static final long EXPIRATION = 3600L;

    // 选择了记住我之后的过期时间为7天
    private static final long EXPIRATION_REMEMBER = 604800L;

    /**
     * 根据用户名创建token
     *
     * @param userName     用户名
     * @param isRememberMe 记住我 true 会保留7天事件 / false 保留默认时间
     * @return
     */
    public static String createToken(String userName, String role, Boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return createToken(userName, role, expiration);
    }

    /**
     * 根据用户名创建时间
     *
     * @param username
     * @param role
     * @param validTime
     * @return
     */
    public static String createToken(String username, String role, long validTime) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, role);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + validTime * 1000))
                .compact();
    }

    public static boolean isExpiration(String token) {
        return getTokenBody(token).getExpiration().before(new Date());
    }

    // 从token中获取用户名
    public static String getUsername(String token) {
        try {
            return getTokenBody(token).getSubject();
        }catch (Exception e){
            log.error("get user is error :{}",e.toString()+e.getMessage(),e);
        }
        return null;
    }

    // 获取用户角色
    public static String getUserRole(String token) {
        try {
            return (String) getTokenBody(token).get(ROLE_CLAIMS);
        }catch (Exception e){
            log.error("get user role is error :{}",e.toString()+e.getMessage(),e);
        }
        return null;
    }


    public static Claims getTokenBody(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static void main(String[] args) {
        long time = Long.valueOf(10);
//        String token = createToken("timo", "ROLE_ADMIN", time);
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0aW1vIiwiaXNzIjoiZWNoaXNhbiIsImV4cCI6MTU1MzE1Njc4NSwiaWF0IjoxNTUzMTU2Nzc1LCJyb2wiOiJST0xFX0FMTCJ9.MHIEg7nuO9cF7rDc91RDSEkwv1KO4i_ZwVmXbiP2P0kUefrRhwUxbSwvpviGps13PVLpuezkDl94OCIHY4F8zA";
        System.out.println(token);
        boolean e = isExpiration(token);
        System.out.println(e);
        String username = getUsername(token);
        System.out.println(username);
        String role = getUserRole(token);
        System.out.println(role);
    }
}
